// 商品查询service
'use strict';
const Service = require('egg').Service;
const { Op } = require('sequelize');

const { failRes, successRes } = require('../extend/helper');
const { Journal } = require('../exception/Journal');

const stringRandom = require('string-random');

function toInt (str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class sProductClass extends Service {
  // pc
  // 查
  async pc_s_query (params) {
    console.log('params: ', params);
    let response = null;
    const { ctx } = this;
    try {
      let label = params?.label ?? '';
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);
      const result = await ctx.model.ProductClass.findAndCountAll({
        where: {
          label: {
            [Op.like]: `%${label}%` // 使用 Op.like 实现模糊匹配
          }
        },
        order: [['id', 'DESC']], // 排序
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      })
      await Journal(ctx, { operatorType: '商品分类 -> 查询', code: 200 });
      response = successRes({
        records: (result?.rows ?? []),
        total: (result?.count ?? 0),
        pageSize,
        currentPage
      });
    } catch (error) {
      console.error(error, '<---- error - 商品分类查询');
      await Journal(ctx, { operatorType: '商品分类 -> 查询', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 增
  async pc_s_create (params) {
    let response = null;
    const { ctx } = this;
    try {
      await ctx.model.ProductClass.create(
        params,
        { attributes: { extends: ['id', 'label', 'remarks'] } } // 向数据库插入特定字段
      );
      await Journal(ctx, { operatorType: '商品分类 -> 新增', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 商品分类新增');
      await Journal(ctx, { operatorType: '商品分类 -> 新增', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 改
  async pc_s_update (params) {
    let response = null;
    try {
      const { ctx } = this;
      await ctx.model.ProductClass.update(
        params,
        {
          where: { id: params.id },
          attributes: { extends: ['id'] }
        }
      );
      await Journal(ctx, { operatorType: '商品分类 -> 编辑', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 商品分类编辑');
      await Journal(ctx, { operatorType: '商品分类 -> 编辑', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 删
  async pc_s_delete (params) {
    let response = null;
    const { ctx } = this;
    try {
      await ctx.model.ProductClass.destroy(
        {
          where: { id: params.id },
        }
      );
      await Journal(ctx, { operatorType: '商品分类 -> 删除', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 商品分类删除');
      await Journal(ctx, { operatorType: '商品分类 -> 删除', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  async pc_c_query_all () { 
    let response = null;
    const { ctx } = this;
    try {
      const result = await ctx.model.ProductClass.findAll({
        order: [['id', 'DESC']], // 排序
      })
      await Journal(ctx, { operatorType: '商品分类 -> 查询(不分页)', code: 200 });
      response = successRes(result);
    } catch (error) {
      console.error(error, '<---- error - 商品分类查询(不分页)');
      await Journal(ctx, { operatorType: '商品分类 -> 查询(不分页)', code: 401 });
      response = failRes(401);
    }
    return response;
  }


  // wa
  // 查
  async wa_s_query () {
    // 查询所有商品分类，并且根据分类查询分类下的商品以及文件
    let response = null;
    try {
      const { ctx } = this;
      // 查询所有商品分类
      const productClasses = await ctx.model.ProductClass.findAll({
        include: [
          {
            // 在分类查询中包含关联的商品
            model: ctx.model.Product,
            include: [
              {
                model: ctx.model.Resource, 
                through: {
                  attributes: {
                    exclude: ['id', 'resourceId', 'productId', 'createdAt', 'updatedAt']
                }}
              }
            ]
          },
        ],
      });
      await Journal(ctx, { operatorType: '商品分类 -> 查询', code: 200 });
      response = successRes(productClasses);
    } catch (error) {
      console.error(error, '<---- error - wa 商品分类查询');
      await Journal(ctx, { operatorType: '商品分类 -> 查询', code: 401 });
      response = failRes(401);
    }
    return response;
  }
}


module.exports = sProductClass;